﻿using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.IO;
using System.Runtime.InteropServices;
using System.Linq;

using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Controls;
using ESRI.ArcGIS.ADF;
using ESRI.ArcGIS.SystemUI;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.Display;

using MyEngineExercise.我的扩展;
using MyEngineExercise.我的扩展.自定义事件参数类;
using MyEngineExercise.我的扩展.枚举;
using ESRI.ArcGIS.Geodatabase;
using MyEngineExercise.我的扩展.窗体;
using MyEngineExercise.我的扩展.绘制多边形;
using MyEngineExercise.我的扩展.open和saveFileDialog扩展;
using System.Text;
using System.Collections.Generic;
using EngineWindowsApplication1.DataLoader;
using System.Diagnostics;
using System.Text.RegularExpressions;
using MyEngineExercise.工作.分割图层_20120810;
using MyEngineExercise.我的扩展.信息类;
using MyEngineExercise.工作.兴宁出图_20121110;


namespace MyEngineExercise
{
    /// <summary>
    /// 主窗体
    /// </summary>
    public sealed partial class MainForm : Form
    {
        #region 字段 + 属性
        /// <summary>
        /// map控件实例
        /// </summary>
        private IMapControl3 _mapControl = null;

        /// <summary>
        /// page控件实例
        /// </summary>
        private IPageLayoutControl3 _pageLayoutControl = null;

        /// <summary>
        /// toc控件实例
        /// </summary>
        private ITOCControl2 _tocControl = null;

        /// <summary>
        /// toolbar实例
        /// </summary>
        private IToolbarControl2 _toolbarControl = null;


        /// <summary>
        /// 控制map和page控件同步的实例
        /// </summary>
        private MapAndPageSync _mapAndPageSync = null;


        /// <summary>
        /// mxd文档完整路径
        /// </summary>
        private string _documentFileName = string.Empty;

        /// <summary>
        /// 打开mxd文档的实例
        /// </summary>
        private OpenNewMapDocument _openMapDoc = null;

        /// <summary>
        /// MyAeExtend实例
        /// </summary>
        private MyAeMethods _myAeMethod = null;

        /// <summary>
        /// 当前活动视图
        /// </summary>
        private IActiveView _currentActiveView = null;

        /// <summary>
        /// toc点击实例
        /// </summary>
        private TocCtrlClick _tocCtrlClick = null;


        /// <summary>
        /// SaveFileDialog包装类，导出jpg时用
        /// </summary>
        private SaveFileDialog_jpg _saveFileDialog_jpg = null;


        /// <summary>
        /// 绘制矩形工具的实例
        /// </summary>
        private EnvelopeFeedbackTool _envelopeFeedbackTool = null;


        private DrawGeometryCompletedToDo _drawGeometryCompletedToDo = DrawGeometryCompletedToDo.None;
        #endregion


        #region class constructor 构造函数
        /// <summary>
        /// 构造函数
        /// </summary>
        public MainForm()
        {
            InitializeComponent();
        }
        #endregion


        #region 非自定义事件处理程序


        #region 控件相关事件处理程序
        /// <summary>
        /// MainForm_Load事件处理程序
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MainForm_Load(object sender, EventArgs e)
        {

            #region 初始化各种实例
            //初始化
            _mapControl = (IMapControl3)axMapControl1.Object;
            _pageLayoutControl = (IPageLayoutControl3)axPageLayoutControl1.Object;
            _tocControl = (ITOCControl2)axTOCControl1.Object;
            _toolbarControl = (IToolbarControl2)axToolbarControl1.Object;

            //默认视图是map视图
            _currentActiveView = _mapControl.ActiveView;

            //创建实例

            _myAeMethod = MyAeMethods.CreateInstance(this, _mapControl, _pageLayoutControl, _tocControl, _toolbarControl);

            _mapAndPageSync = MapAndPageSync.CreateInstance(_mapControl, _pageLayoutControl, _tocControl, _toolbarControl, this);
            
            
            
            //导出jpg的saveFileDialog
            _saveFileDialog_jpg = new SaveFileDialog_jpg();

            #endregion

 
            #region 自定义工具栏
            //add the Open Map Document command onto the toolbar
            _openMapDoc = new OpenNewMapDocument(_mapAndPageSync);
            axToolbarControl1.Remove(0);//替换掉第一个工具，因为和将要添加的工具功能重复
            axToolbarControl1.AddItem(_openMapDoc, -1, 0, false, -1, esriCommandStyles.esriCommandStyleIconOnly);

            //添加绘制矩形工具
            _envelopeFeedbackTool = new EnvelopeFeedbackTool(toolStripStatusLabel3);
            axToolbarControl1.AddItem(_envelopeFeedbackTool, -1, -1, true, 0, esriCommandStyles.esriCommandStyleIconOnly);
            #endregion


            #region 初始化各种控件

            //disable the Save menu (since there is no document yet)
            menuSaveDoc.Enabled = false;

            //设置选项卡标题
            this.tabPage1.Text = "Map";
            this.tabPage2.Text = "Layout";

            this.toolStripStatusLabel1.Text = "#数据视图#";

            //画矩形
            envelopToolStripMenuItem.Tag = _envelopeFeedbackTool;
            #endregion



            #region 加入事件处理程序

            _mapAndPageSync.ActiveViewChanged += new EventHandler<ActiveViewChangedEventArg>(mapOrPage_ActiveViewChangedEventArg);

            _myAeMethod.LayerChanging += new EventHandler<LayerChangingEventArgs>(LayerChanging);
            _myAeMethod.LayerChanged += new EventHandler<LayerChangedEventArgs>(LayerChanged);

            _envelopeFeedbackTool.GeometryComplete += new EventHandler<GeometryCompleteArgs>(DrawGeometryCompleted);


            this.tabControl1.SelectedIndexChanged += delegate
            {
                if (this.tabControl1.SelectedIndex == 0)
                    _mapAndPageSync.ActivateMap();
                else if (this.tabControl1.SelectedIndex == 1)
                    _mapAndPageSync.ActivatePageLayout();
            };
            #endregion
        }


        /// <summary>
        /// listen to MapReplaced evant in order to update the statusbar and the Save menu
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void axMapControl1_OnMapReplaced(object sender, IMapControlEvents2_OnMapReplacedEvent e)
        {
            //get the current document name from the _openMapDoc
            _documentFileName = _openMapDoc.DocumentFileName;

            //if there is no MapDocument, diable the Save menu and clear the statusbar
            if (_documentFileName == string.Empty)
            {
                menuSaveDoc.Enabled = false;
                mapXYStatusLabel.Text = string.Empty;
            }
            else
            {
                //enable the Save manu and write the doc name to the statusbar
                menuSaveDoc.Enabled = true;
                mapXYStatusLabel.Text = System.IO.Path.GetFileName(_documentFileName);
            }
        }


        private void axMapControl1_OnMouseMove(object sender, IMapControlEvents2_OnMouseMoveEvent e)
        {
            mapXYStatusLabel.Text = string.Format("{0}, {1}  {2}", e.mapX.ToString("#######.##"), e.mapY.ToString("#######.##"), axMapControl1.MapUnits.ToString().Substring(4));

            if (this._currentActiveView is IMap)//page视图
            {
                pageXYStatusLabel.Text = string.Empty;
            }
        }


        private void axPageLayoutControl1_OnMouseMove(object sender, IPageLayoutControlEvents_OnMouseMoveEvent e)
        {
            //page视图时，在状态栏上显示map坐标
            //获取点坐标在哪个map上
            IActiveView activeView = this._pageLayoutControl.ActiveView;
            IPoint hitPoint = activeView.ScreenDisplay.DisplayTransformation.ToMapPoint(e.x, e.y);
            IMap hitMap = activeView.HitTestMap(hitPoint);//获取焦点地图

            if (null != hitMap)
            {
                IActiveView mapActiveView = (IActiveView)hitMap;//获取当前焦点地图的活动视图
                IDisplayTransformation displayTransformation = mapActiveView.ScreenDisplay.DisplayTransformation;
                IPoint point = displayTransformation.ToMapPoint(e.x, e.y);
                mapXYStatusLabel.Text = string.Format("{0}, {1}  {2}", point.X.ToString("#######.##"), point.Y.ToString("#######.##"), displayTransformation.Units);
            }
            else
                mapXYStatusLabel.Text = string.Empty;

            pageXYStatusLabel.Text = string.Format("{0}, {1}  {2}", e.pageX.ToString("#######.##"), e.pageY.ToString("#######.##"),this._pageLayoutControl.Page.Units);
        }


        /// <summary>
        /// 点击tic控件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void axTOCControl1_OnMouseDown(object sender, ITOCControlEvents_OnMouseDownEvent e)
        {
            _tocCtrlClick = TocCtrlClick.Init(_tocControl, e.x, e.y);

            if (e.button == 2 && _tocCtrlClick.IsHitLayerItem)//鼠标右键
            {
                if (_tocCtrlClick.IsHitShapeLayerItem)//判断点击的项数据源是否shapefile文件
                    this.shapefileLayer_contextMenuStrip1.Show(this.axTOCControl1,e.x,e.y);//弹出右键菜单
                if (_tocCtrlClick.IsHitMdbLayerItem)//判断点击的项数据源是否mdb文件
                    this.mdbLayer_contextMenuStrip1.Show(this.axTOCControl1, e.x, e.y);
            }
        }


        /// <summary>
        /// shape文件右键菜单打开前
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void shapefileLayer_contextMenuStrip1_Opening(object sender, CancelEventArgs e)
        {
            //设置菜单的项是否可用
            ILayer layer = _tocCtrlClick.HitLayer;
            bool enable = layer.Valid && (layer is IFeatureLayer);

            foreach (ToolStripItem item in shapefileLayer_contextMenuStrip1.Items)
                item.Enabled = enable;

            if (!enable)
                return;

            bool isHasRecord = _tocCtrlClick.FeatureClass.IsHasRecord();
            bool isPolygon = _tocCtrlClick.FeatureClass.IsPolygon();
            flashPolygonToolStripMenuItem.Enabled = isHasRecord && isPolygon;//闪烁项目
            locatPolygonToolStripMenuItem.Enabled = isHasRecord;//定位项目
        }

        #endregion


        #region （“File”菜单事件处理程序）Main Menu event handlers
        /// <summary>
        /// New Document
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void menuNewDoc_Click(object sender, EventArgs e)
        {
            MyAeMethods.Instance.SetBusyState();

            //ask the user whether he'd like to save th ecurrent doc
            DialogResult res = MessageBox.Show("Would you like to save the current document?", "Message", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (res == DialogResult.Yes)
            {
                //if yes, launch the SaveAs command
                ICommand command = new ControlsSaveAsDocCommandClass();
                command.OnCreate(_mapAndPageSync.PageLayoutControl.Object);
                command.OnClick();
            }

            // switch to map view
            tabControl1.SelectedTab = (TabPage)tabControl1.Controls[0];

            //创建一个空的新的map
            //create a new Map instance
            IMap map = new MapClass();
            map.Name = "Map";
            //replace the shared map with the new Map instance
            _mapAndPageSync.ReplaceMap(map);

            _documentFileName = string.Empty;

            MyAeMethods.Instance.SetDefaultState();
        }

        /// <summary>
        /// Open Document...
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void menuOpenDoc_Click(object sender, EventArgs e)
        {
            MyAeMethods.Instance.SetBusyState();
            //Application.DoEvents();

            //this._mapControl.MousePointer = esriControlsMousePointer.esriPointerParentWindow;
            // switch to map view
            //tabControl1.SelectedTab = (TabPage)tabControl1.Controls[0];

            //launch the OpenMapDoc command
            _openMapDoc = new OpenNewMapDocument(_mapAndPageSync);
            _openMapDoc.OnCreate(_mapAndPageSync.MapControl.Object);
            _openMapDoc.OnClick();

            MyAeMethods.Instance.SetDefaultState();
        }

        /// <summary>
        /// SaveDocument
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void menuSaveDoc_Click(object sender, EventArgs e)
        {
            MyAeMethods.Instance.SetBusyState();

            //make sure that the current MapDoc is valid first
            if (_documentFileName != string.Empty && _mapControl.CheckMxFile(_documentFileName))
            {
                //create a new instance of a MapDocument class
                IMapDocument mapDoc = new MapDocumentClass();
                //Open the curent document into the MapDocument
                mapDoc.Open(_documentFileName, string.Empty);

                //Replace the map with the one of the PageLayout
                mapDoc.ReplaceContents((IMxdContents)_pageLayoutControl.PageLayout);

                //save the document
                mapDoc.Save(mapDoc.UsesRelativePaths, false);
                mapDoc.Close();
            }

            MyAeMethods.Instance.SetDefaultState();
        }

        /// <summary>
        /// Save As...
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void menuSaveAs_Click(object sender, EventArgs e)
        {
            MyAeMethods.Instance.SetBusyState();

            //launch the SaveAs command. Always use the PageLayoutControl in order to keep 
            // all of the map surrounds. 
            ICommand command = new ControlsSaveAsDocCommandClass();
            command.OnCreate(_mapAndPageSync.PageLayoutControl.Object);
            command.OnClick();

            MyAeMethods.Instance.SetDefaultState();
        }

        /// <summary>
        /// Exit
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void menuExitApp_Click(object sender, EventArgs e)
        {
            //exit the application
            Application.Exit();
        }
        #endregion


        #region “how to” 菜单点击事件，事件处理程序
        /// <summary>
        /// How to add a layer to a map from a layer file 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void howToAddALayerToAMapFromALayerFileToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            if (openFileDialog.ShowDialog(this) == DialogResult.OK)
            {
                this.Cursor = Cursors.WaitCursor;
                try
                {
                    ExampleMethods.AddLayerFileToMap(_mapControl.Map, openFileDialog.FileName);
                }
                catch
                {
                    MessageBox.Show("mxd中没有map或layer", "错误！", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                this.Cursor = Cursors.Default;
            }
        }

        /// <summary>
        /// How to access maps and layers via the MapDocument 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void howToAccessMapsAndLayersViaTheMapDocumentToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            if (openFileDialog.ShowDialog(this) == DialogResult.OK)
            {
                this.Cursor = Cursors.WaitCursor;
                ExampleMethods.OpenMXDViaMapDocument(openFileDialog.FileName);
                this.Cursor = Cursors.Default;
            }
        }

        /// <summary>
        /// AddShapeFile
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void addShapeFileToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Cursor = Cursors.WaitCursor;
            ExampleMethods.AddShapeFile(_mapControl.Map);
            this.Cursor = Cursors.Default;
        }
        #endregion


        #region "输出jpg"菜单事件处理程序
        /// <summary>
        /// 输出全图
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void exportFullToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (_saveFileDialog_jpg.SaveFileDialog.ShowDialog(this) == DialogResult.OK)
            {
                _myAeMethod.ExportJpg(
                    _mapAndPageSync.ActiveView,
                    _mapAndPageSync.ActiveView.FullExtent,
                    200,
                    _saveFileDialog_jpg.SaveFileDialog.FileName,
                    true);
            }
        }


        /// <summary>
        /// 输出当前窗口
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void exportViewToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (_saveFileDialog_jpg.SaveFileDialog.ShowDialog(this) == DialogResult.OK)
            {
                _myAeMethod.ExportJpg(
                    _mapAndPageSync.ActiveView,
                    _mapAndPageSync.ActiveView.Extent,
                    200,
                    _saveFileDialog_jpg.SaveFileDialog.FileName,
                    false);
            }
        }


        /// <summary>
        /// 输出选择的区域
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void exportSelectToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //查找工具栏上的工具
            ITool drawEnvelopTool = axToolbarControl1.FindTool<EnvelopeFeedbackTool>();
            //如果查找到工具 且 工具可用
            if (null != drawEnvelopTool && ((ICommand)drawEnvelopTool).Enabled)
            {
                axToolbarControl1.CurrentTool = drawEnvelopTool;
                _drawGeometryCompletedToDo = DrawGeometryCompletedToDo.ExportJpg;
            }
            else
                MessageBox.Show("不是map视图 或 工具不可用");
        }
        #endregion


        #region “用地分析”菜单事件处理程序
        /// <summary>
        /// 打开项目红线
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void openRedLineToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //MessageBox.Show(Environment.CurrentDirectory.Replace("\\bin\\Debug",String.Empty));
            OpenFileDialog_redLine openFileDialog_redLine = new OpenFileDialog_redLine();

            if (openFileDialog_redLine.OpenFileDialog.ShowDialog(this) == DialogResult.OK)
            {
                IFeatureClass redFeatureClass = MyAeMethods.Instance.NewFeatureClass(openFileDialog_redLine.OpenFileDialog.FileName);

                if (null == redFeatureClass)
                    MessageBox.Show("错误：无法打开该Shape文件。\n" + openFileDialog_redLine.OpenFileDialog.FileName, "打开项目红线", MessageBoxButtons.OK, MessageBoxIcon.Error);
                else
                {
                    if (redFeatureClass.ShapeType != esriGeometryType.esriGeometryPolygon)
                        MessageBox.Show("该shape文件不是一个面文件", "打开项目红线", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    else if (redFeatureClass.IsHasRecord() == false)
                        MessageBox.Show("该红线没有记录！", "打开项目红线", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    else
                    {
                        IFeatureLayer redFeatureLayer = MyAeMethods.Instance.NewRedFeatureLayer(redFeatureClass);
                        _myAeMethod.AddLayer(redFeatureLayer);
                    }
                }
            }
        }


        /// <summary>
        /// 画多边形、矩形、线形
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DrawGeometryMenuItem_Click(object sender, EventArgs e)
        {
            /*if(_mapAndPageSync.FocusMap.LayerCount <= 0)
            {
                MessageBox.Show("请先添加一些图层","新建项目红线",MessageBoxButtons.OK,MessageBoxIcon.Information);
                return;
            }*/

            ITool drawTool = ((ToolStripMenuItem)sender).Tag as ITool;

            if (null == drawTool)
            {
                MessageBox.Show("找不到画图工具！");
            }

            if (((ICommand)drawTool).Enabled)
            {
                axToolbarControl1.CurrentTool = drawTool;
                _drawGeometryCompletedToDo = DrawGeometryCompletedToDo.CreateRedLine;
            }
            /*else
                MessageBox.Show("请先转换为数据视图");*/
        }



        /// <summary>
        /// 删除项目红线
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void deleteRedLineToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFileDialog_DeleteRedLine openFileDialog_DeleteRedLine = new OpenFileDialog_DeleteRedLine();
            if (openFileDialog_DeleteRedLine.OpenFileDialog.ShowDialog(this) != DialogResult.OK)
                return;

            //用户选择的，待删除的shape文件集合
            var toDeleteShapeFiles = openFileDialog_DeleteRedLine.OpenFileDialog.FileNames
                .Select(v => MyAeMethods.Instance.NewFeatureClass(v))
                .Where(v => null != v)
                .Select(v => (IDataset)v);

            //保存删除失败时，删除失败的图层名的字符串
            StringBuilder deleteFail = new StringBuilder();//可变的string
            //保存删除成功时，删除成功的图层名的字符串
            StringBuilder deleteSuccess = new StringBuilder();

            //冲突的图层名，记录删除图层时候，已加载图层的图层名
            List<String> conflictLayerNames = new List<String>();
            //删除图层时，待删除的图层是否已加载
            Boolean isConflict = false;

            ////当前地图窗口已以有的图层名称的列表
            List<String> existedLayerNameList = MyAeMethods.Instance.AllExistedLayerList().Select(v => v.Name).ToList();

            //判断要删除的项目红线是否加载中
            foreach (IDataset toDeleteShapeFile in toDeleteShapeFiles)
            {
                if (existedLayerNameList.Contains(toDeleteShapeFile.Name))
                {
                    isConflict = true;
                    conflictLayerNames.Add(toDeleteShapeFile.Name);
                }
            }

            //如果已经加载，询问用户
            if (isConflict)
            {
                string str = String.Empty;

                foreach (var name in conflictLayerNames)
                    str += name.ToString() + "\n";

                if (MessageBox.Show("项目红线：\n" + str + "\n已加载，是否继续？", "删除项目红线", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
                    return;


                /*//删除已加载的图层（为什么删除不了），因为toRemoveLayers集合中的图层没有加载到图层中，要用控件获取加载的图层
                var toRemoveLayers = openFileDialog_DeleteRedLine.OpenFileDialog.FileNames
                    .Select(v => (ILayer)MyAeMethods.NewFeatureLayer(v))
                    .Where(v => null != v && conflictLayerNames.Contains(v.Name));

                //MessageBox.Show(toRemoveLayers.Count().ToString());
                _myAeMethod.DeleteLayers(toRemoveLayers);
                Application.DoEvents();*/

                List<ILayer> layers = MyAeMethods.Instance.AllExistedLayerList();
                foreach (var layer in layers)
                {
                    if (conflictLayerNames.Contains(layer.Name))
                        _myAeMethod.DeleteLayer(layer);
                }

            }
            


            //开始删除shapefile
            foreach (IDataset toDeleteShapeFile in toDeleteShapeFiles)
            {
                try
                {
                    toDeleteShapeFile.Delete();//删除dataset，删除shape文件
                    deleteSuccess.Append(toDeleteShapeFile.Name);
                    deleteSuccess.Append(",");
                    //MessageBox.Show(toDeleteShapeFile.Name);
                }
                catch
                {
                    deleteFail.Append(toDeleteShapeFile.Name);
                    deleteFail.Append(",");
                }
            }


            //提示删除成功或失败信息
            if (deleteFail.Length > 0)
            {
                String headStr = String.Empty;
                if (deleteSuccess.Length > 0)
                    headStr = "文件：\n" + deleteSuccess.ToString() + "\n删除成功！\n";

                MessageBox.Show(headStr + "下列文件无法删除:\n" + deleteFail.ToString(), "删除项目红线", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }    
            else
                MessageBox.Show("删除成功！", "删除项目红线");
        }
        #endregion


        #region toc控件右键菜单

        /// <summary>
        /// 打开文件属性表，shaoefile、mdb
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void openAttributeTableToolStripMenuItem_Click(object sender, EventArgs e)
        {
            IFeatureClass featureClass = _tocCtrlClick.FeatureClass;

            if (null == featureClass)
            {
                MessageBox.Show(String.Format("没法打开{0}图层的属性表", ((IDataset)featureClass).Name), "打开属性表", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (featureClass.IsShapeFile())//打开shapefile文件属性表
            {
                if (featureClass.CanFieldTypeToDataTableType())
                {
                    RedLayerAttributeTableForm redLayerAttributeTableForm = new RedLayerAttributeTableForm(featureClass);
                    redLayerAttributeTableForm.ShowDialog(this);
                }
                else
                    MessageBox.Show(String.Format("无法打开{0}图层的属性表，因为缺少必要的字段！",((IDataset)featureClass).Name), "打开属性表", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else if(featureClass.IsInMdbFile())//打开mdb文件属性表
            {
                MessageBox.Show("打开mdbLayer属性表");
            }

            
        }

        /// <summary>
        /// 关闭图层
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void closeLayerToolStripMenuItem_Click(object sender, EventArgs e)
        {
            _myAeMethod.DeleteLayer(_tocCtrlClick.FeatureLayer);  
        }


        /// <summary>
        /// 闪烁项目
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void flashPolygonToolStripMenuItem_Click(object sender, EventArgs e)
        {
            IFeatureClass featureClass = _tocCtrlClick.FeatureClass;
            if (featureClass.FeatureCount(null) <= 100)
            {
                IPolygon polygon = UnionFeatureLayerPolgons(_tocCtrlClick.FeatureLayer);
                if (null != polygon)
                    _mapAndPageSync.DoHookAction(polygon, esriHookActions.esriHookActionsFlash);
            }
            else
                MessageBox.Show("图层记录超过100条，无法同时闪烁！","记录太多！",MessageBoxButtons.OK,MessageBoxIcon.Warning);
        }


        /// <summary>
        /// 定位项目
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void locatPolygonToolStripMenuItem_Click(object sender, EventArgs e)
        {
            _mapAndPageSync.DoHookAction(_tocCtrlClick.FeatureLayer.AreaOfInterest, esriHookActions.esriHookActionsZoom);
        }


        /// <summary>
        /// 数据来源
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dataComeFromToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FeatureLayerInfoForm featureLayerInfoForm = new FeatureLayerInfoForm(_tocCtrlClick.FeatureLayer);
            featureLayerInfoForm.ShowDialog(this);
        }
        #endregion

        #endregion


        #region 自定义事件处理程序
        /// <summary>
        /// 事件处理程序：ActiveViewChanged
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void mapOrPage_ActiveViewChangedEventArg(object sender, ActiveViewChangedEventArg e)
        {
            IActiveView activeView=e.ActiveView;

            if (activeView is IMap)
            {
                this.toolStripStatusLabel1.Text = "#数据视图#";
                _currentActiveView = activeView;
            }
            else
            {
                this.toolStripStatusLabel1.Text = "#布局视图#";
                _currentActiveView = activeView;
            }
        }


        /// <summary>
        /// 图层操作前：如删除、添加
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void LayerChanging(object sender, LayerChangingEventArgs e)
        {
            if (e.Cancel)
                return;

            if (!(e.Layer is IFeatureLayer))//如果不是IFeatureLayer
            {
                MessageBox.Show("不允许加载非 FeatureLayer 图层","加载图层",MessageBoxButtons.OK,MessageBoxIcon.Error);
                e.Cancel = true;
                return;
            }


            //添加图层操作
            if (e.LayerAction == LayerAction.Add && e.Layer.Valid)
            {
                IFeatureClass featureClass=((IFeatureLayer)e.Layer).FeatureClass;

                //检查坐标系
                IGeoDataset geoDataset = (IGeoDataset)featureClass;
                int referanceCode = geoDataset.SpatialReference.FactoryCode;
                //...


                // 已经加载的Shape文件不允许再次加载
                var workspaceType = ((IDataset)featureClass).Workspace.Type;
                if (workspaceType == esriWorkspaceType.esriFileSystemWorkspace)
                {
                    if(MyAeMethods.Instance.IsContainFeatureClass(featureClass))
                    {
                        MessageBox.Show("文件\n" + featureClass.GetFullPath() + "\n已经加载！","加载图层",MessageBoxButtons.OK,MessageBoxIcon.Warning);
                        e.Cancel = true;
                        return;
                    }
                }
            }


            //删除图层操作
            //检查有没有窗口正在使用这个图层
            if (e.LayerAction == LayerAction.Remove)
            {
                //MessageBox.Show("in layerchanging");
            }
        }


        /// <summary>
        /// 图层操作后：如删除、添加
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void LayerChanged(object sender, LayerChangedEventArgs e)
        {
            if (e.Cancel)
                return;

            //添加图层
            if (e.LayerAction == LayerAction.Add)
            {
                var latestLayer = e.Layers.Last();//返回最新的图层

                if (latestLayer is IFeatureLayer && latestLayer.Valid)
                {
                    IFeatureLayer featureLayer = (IFeatureLayer)latestLayer;
                    IFeatureClass featureclass = featureLayer.FeatureClass;

                    //if(Path.)
                    //MessageBox.Show("LayerChanged   " + featureclass.GetFullPath());
                    if (featureclass.IsHasRecord() && featureclass.IsShapeFile() && featureclass.IsPolygon() && featureclass.HasOID)
                        _mapAndPageSync.DoHookAction(featureLayer.AreaOfInterest, esriHookActions.esriHookActionsZoom); //定位图层

                    if (!featureclass.HasOID)
                    {
                        try
                        {
                            IClassSchemaEdit classSchemaEdit = (IClassSchemaEdit)featureclass;
                            //将FID字段，注册为ObjectID字段
                            classSchemaEdit.RegisterAsObjectClass("FID", String.Empty);
                        }
                        catch (Exception ex)
                        {
                            throw ex;
                        }
                    }

                }
            }


            //删除图层
            if (e.LayerAction == LayerAction.Remove)
            {
                //MessageBox.Show("in layerchanged");
            }
        }


        /// <summary>
        /// 几何图形绘制完成后
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DrawGeometryCompleted(object sender, GeometryCompleteArgs e)
        {
            //toolStripStatusLabel3.Text = "#显示画几何图形面积、长度等#";

            if (_drawGeometryCompletedToDo == DrawGeometryCompletedToDo.ExportJpg)
            {
                #region 导出jpg操作

                //MessageBox.Show("导出jpg");
                if (_saveFileDialog_jpg.SaveFileDialog.ShowDialog(this) == DialogResult.OK)
                {
                    _myAeMethod.ExportJpg(
                        _mapAndPageSync.ActiveView,
                        (IEnvelope)e.Geometry,
                        200,
                        _saveFileDialog_jpg.SaveFileDialog.FileName,
                        false);
                }

                _drawGeometryCompletedToDo = DrawGeometryCompletedToDo.None;
                axToolbarControl1.CurrentTool = null;//设置当前工具为空
                #endregion
            }
            else if (_drawGeometryCompletedToDo == DrawGeometryCompletedToDo.CreateRedLine)
            {
                #region 创建项目红线
                //MessageBox.Show("创建项目红线！");

                #region 判断多边形的类型，如果是线类型，要设置缓冲区
                IPolygon redLinePolygon = null;

                //判断几何图形的类型
                switch (e.Geometry.GeometryType)
                {
                    case esriGeometryType.esriGeometryEnvelope: //Envelope类型
                        redLinePolygon = MyAeMethods.Instance.EnvelopToPolygonClass((IEnvelope)e.Geometry, MyAeMethods.Instance.GetSpatialReference_Xian1980_3_38());//转换为polygon
                        break;

                    default:
                        break;

                }

                #endregion

                //要求用户输入红线的非空间信息
                InputRedLineInfoForm inputRedLineInfoForm = new InputRedLineInfoForm((IPolygon4)redLinePolygon);
                if (inputRedLineInfoForm.ShowDialog(this) != DialogResult.OK)
                    return;

                //默认存放项目红线的文件夹路径
                //String redLineFolder = Constants.RED_LINE_FOLDER_PATH;

                //提示用户选择保存的路径
                SaveFileDialog_redLine saveFileDialog_redLine = new SaveFileDialog_redLine();
                if (saveFileDialog_redLine.SaveFileDialog.ShowDialog(this) != DialogResult.OK)
                    return;

                MyAeMethods.Instance.SetBusyState();
                Application.DoEvents();

                //创建featureclass
                IFeatureClass redLineFeatureClass = MyAeMethods.Instance.CreateRedLineFeatureClass(saveFileDialog_redLine.SaveFileDialog.FileName);

                if (null == redLineFeatureClass)
                {
                    MessageBox.Show("无法创建FeatureClass");
                    MyAeMethods.Instance.SetDefaultState();
                    return;
                }


                //往featureclass中写入数据
                Boolean isAddSuccess = MyAeMethods.Instance.AddDataToFeatureClass(redLineFeatureClass, inputRedLineInfoForm.RedLineRowInfo);


                if (isAddSuccess)
                {
                    //向控件中添加图层
                    IFeatureLayer toAddFeatureLayer = MyAeMethods.Instance.NewRedFeatureLayer(redLineFeatureClass);
                    MyAeMethods.Instance.AddLayer(toAddFeatureLayer);
                }
                else
                    MessageBox.Show("没法添加图层", "创建shapefile");


                MyAeMethods.Instance.SetDefaultState();
                #endregion
            }
            else
            {
                //显示面积
                //MessageBox.Show(((IArea)((IEnvelope)e.Geometry)).Area.ToString());
                MessageBox.Show("绘制几何图形后没有操作！");
            }
        }
        #endregion


        #region 其他函数

        /// <summary>
        /// 合并多边形
        /// </summary>
        /// <param name="featureLayer"></param>
        /// <returns></returns>
        private IPolygon UnionFeatureLayerPolgons(IFeatureLayer featureLayer)
        {
            if (!featureLayer.Valid)
                return null;

            IFeatureClass featureClass = featureLayer.FeatureClass;

            if (!featureClass.IsPolygon() || !featureClass.IsHasRecord()) return null;

            toolStripStatusLabel2.Text = "正在合并图斑...";
            MyAeMethods.Instance.SetBusyState();
            this.axTOCControl1.Enabled = false;
            Application.DoEvents();

            IPolygon polygon = featureClass.UnionPolygons(String.Empty);

            toolStripStatusLabel2.Text = "完成";
            MyAeMethods.Instance.SetDefaultState();
            this.axTOCControl1.Enabled = true;
            Application.DoEvents();

            return polygon;
        }

        #endregion



        private void 获取datasetNameToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DatasetListForm datasetListForm = new DatasetListForm();
            datasetListForm.ShowDialog(this);
        }

        private void 兴宁出图201211101026ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //inputForm inputForm = new inputForm();
            //inputForm.ShowDialog();

            //IFeatureClass ploygonFeatureClass = _myAeMethod.NewFeatureClass(@"D:\My Documents\Downloads\兴宁处理\测试结果2012_11_08_1642\刁坊镇\原输出坐标检查\2012_11_8_16_42_54\刁坊镇权属区\刁坊镇权属区.shp");
            //IFeatureClass pointFeatureClass = null;
            //IFeatureClass lineFeatureClass = null;
            //IFeatureWorkspace featureWorkspace = _myAeMethod.NewMdbFeatureWorkspace(@"D:\My Documents\Downloads\兴宁处理\测试结果2012_11_08_1642\刁坊镇\原输出坐标检查\2012_11_8_16_42_54\刁坊镇.mdb");
            //pointFeatureClass = featureWorkspace.OpenFeatureClass("景标界址点");
            //lineFeatureClass = featureWorkspace.OpenFeatureClass("景标界址线");
            //string mdbpath = @"D:\资料\luo\兴宁农村集体土地登记发证a3模版一.mxd";
            ExportForm exportForm = new ExportForm(_myAeMethod);
            exportForm.ShowDialog();
        }

        private void 兴宁出图类201211101026ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ExportJpgByQsdwm exportJpgByQsdwm = new ExportJpgByQsdwm(_myAeMethod);
            exportJpgByQsdwm.StartExport();
        }







    }
}